<template>
  <view class="bg-gray-50">
    <!-- 医院信息区域 -->

    <Care />

    <!-- 常规项目区域 -->
    <view class="bg-white mx-2 mt-4 p-4 shadow-sm">
      <view class="flex items-center justify-between">
        <text class="text-[30rpx] font-semibold text-gray-800">常规项目*</text>
        <view class="flex items-center text-gray-500 text-[28rpx]" @click="toggleCustom">
          <text>{{ isCustomExpanded ? "收起" : "展开" }}</text>
          <IconFont :name="isCustomExpanded ? 'arrow-up' : 'arrow-down'" size="12" class="ml-2" />
        </view>
      </view>

      <!-- 动态健康项目 -->
      <view v-show="isCustomExpanded" class="mt-6">
        <!-- 加载状态 -->
        <view v-if="loading" class="flex items-center justify-center py-8">
          <text class="text-gray-500">加载中...</text>
        </view>

        <!-- 固定健康项目列表 -->
        <view class="space-y-3">
          <view v-for="item in fixedHealthItems" :key="item.name" class="bg-white rounded-xl p-4 shadow-sm border border-gray-50 hover:shadow-md transition-shadow duration-200">
            <view class="flex items-center">
              <!-- 图标区域 -->
              <view class="relative">
                <view class="w-12 h-12 rounded-xl flex items-center justify-center mr-4 bg-green-500">
                  <IconFont :name="getIconByName(item.name)" size="20" color="white" />
                </view>
                <!-- 状态指示点 -->
                <view class="absolute -top-1 -right-1 w-4 h-4 rounded-full border-2 border-white" :class="getHealthStatus(item.name, item.value).dotColor || 'bg-green-400'"> </view>
              </view>

              <!-- 内容区域 -->
              <view class="flex-1 min-w-0">
                <view class="flex items-center justify-between mb-2">
                  <text class="text-[30rpx] font-semibold text-gray-800 truncate">{{ item.name }}</text>
                  <view class="px-3 py-1 rounded-full text-[24rpx] font-medium shadow-sm" :class="getHealthStatus(item.name, item.value).color">
                    {{ getHealthStatus(item.name, item.value).status }}
                  </view>
                </view>
                <view class="text-[32rpx] text-gray-600 mb-3">
                  {{ item.value || '暂无数据' }}
                </view>

                <!-- 操作按钮 -->
                <view class="flex items-center space-x-2">
                  <view class="flex items-center px-3 py-1.5 rounded-lg bg-blue-50 hover:bg-blue-100 transition-colors duration-200" @click="editHealthRecord(item)">
                    <IconFont name="edit" size="14" color="#3b82f6" />
                    <text class="text-[24rpx] text-blue-600 ml-1">编辑</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 空状态提示已移除，因为现在显示固定项目列表 -->
      </view>
    </view>
  </view>

  <!-- 编辑弹窗 -->
  <nut-popup v-model:visible="showEditPopup" position="center">
    <view class="relative bg-white p-[40rpx] w-600rpx shadow-xl">
      <!-- 关闭按钮 -->
      <!-- <view class="btsc w-8 h-8 rounded-full bg-gray-100 flex-cneter cursor-pointer hover:bg-gray-200 transition-colors duration-200" @click="cancelEdit">
        <IconFont name="close" size="16" color="#666"></IconFont>
      </view> -->

      <!-- 标题 -->
      <view class="flex items-center justify-between mb-6">
        <text class="text-[32rpx] font-bold text-gray-800">编辑健康数据</text>
        <IconFont name="close" size="16" color="#666" @click="cancelEdit"></IconFont>
      </view>

      <!-- 当前数据展示 -->
      <view class="w-full mb-6 p-4 bg-gray-50 rounded-xl box-border">
        <text class="text-[28rpx] text-gray-600 mb-2 block">当前数值</text>
        <text class="text-[28rpx] font-semibold text-gray-800"> {{ editingRecord?.name || editingRecord?.subName }}：{{ editingRecord?.value || editingRecord?.subRes || '暂无数据' }} </text>
      </view>

      <!-- 输入框 -->
      <view class="w-full mb-6">
        <text class="text-[28rpx] text-gray-700 mb-3 block">新数值</text>
        <input
          v-model="editValue"
          type="digit"
          class="w-full box-border p-4 border-2 border-gray-200 rounded-xl border-1 border-[#eee] text-[40rpx] focus:border-blue-400 focus:outline-none transition-colors duration-200"
          placeholder="请输入新的数值"
        />
      </view>

      <!-- 按钮组 -->
      <view class="flex box-border space-x-4 w-full">
        <nut-button type="default" size="large" class="flex-1 h-12 rounded-xl" @click="cancelEdit"> 取消 </nut-button>
        <nut-button type="primary" size="large" class="flex-1 h-12 rounded-xl" @click="confirmEdit"> 确认修改 </nut-button>
      </view>
    </view>
  </nut-popup>
</template>

<script setup lang="ts">
import { IconFont } from "@nutui/icons-vue-taro";
import { ref, onMounted, computed, onUnmounted } from "vue";
import { useHealthStore } from "@/store/modules/health";
import Care from "@/components/basic-comm/care.vue";
import { request } from "@/service/request";
import Taro from "@tarojs/taro";
import { useEmitter } from "@/hooks/common";
import { localStg } from "@/utils";
import { useDemographicInfoStore } from "@/store";

const healthStore = useHealthStore();
const emitter = useEmitter();

// 健康数据
const healthData = ref<any[]>([]);
const loading = ref(false);

// 固定健康项目列表
const fixedHealthItems = ref([
  { name: '血压心率', value: '', unit: 'mmHg/bpm' },
  { name: '血氧', value: '', unit: '%' },
  { name: '血糖', value: '', unit: 'mmol/L' },
  { name: '体温', value: '', unit: '°C' },
  { name: '血脂', value: '', unit: 'mmol/L' },
  { name: '尿酸', value: '', unit: 'μmol/L' },
  { name: '睡眠评分', value: '', unit: '分' },
  { name: 'BMI', value: '', unit: 'kg/m²' },
  { name: '体重', value: '', unit: 'kg' },
  { name: '运动其他', value: '', unit: '' }
]);

// 编辑相关状态
const showEditPopup = ref(false);
const editingRecord = ref<any>(null);
const editValue = ref("");

// 定义是否展开自定义区域的状态
const isCustomExpanded = ref(true);

// 判断是否为固定健康项目
const isFixedHealthItem = computed(() => {
  if (!editingRecord.value) return false;
  
  const fixedItemNames = [
    '血压心率',
    '血氧',
    '血糖',
    '体温',
    '血脂',
    '尿酸',
    '睡眠评分',
    'BMI',
    '体重',
    '运动其他'
  ];
  
  const itemName = editingRecord.value.name || editingRecord.value.subName;
  return fixedItemNames.includes(itemName);
});

// const demographicStore = useDemographicInfoStore()
// 切换自定义区域的展开状态
const toggleCustom = () => {
  isCustomExpanded.value = !isCustomExpanded.value;
};

// 获取健康数据
const getHealthData = async () => {
  loading.value = true;
  try {
    const obj = localStg.get("demographicInfo");
    if(!obj){
      console.log("获取人口统计学信息失败,无法获取健康数据");
      return;
    }
    const { error, success } = await request.get(
      "/health_records/health_basepro/healthBaseProjectInfo/queryByRecordId",
      {
        recordID: obj.recordid,
        idNumber: obj.idNumber,
      },
      {
        useErrMsg: true,
      }
    );
    // console.log("res article ===", success, error);
    if (!error && success) {
      healthData.value = (success as any).records || [];
    }
  } catch (error) {
    console.error("获取健康数据失败:", error);
    Taro.showToast({
      title: "获取数据失败",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 根据项目名称获取图标
const getIconByName = (subName: string) => {
  const iconMap: Record<string, string> = {
    血糖: "droplet",
    血氧: "droplet",
    血压: "heart",
    心率: "heart",
    体温: "thermometer",
    心电图: "chart-line",
    运动: "running",
  };
  return iconMap[subName] || "droplet";
};

// 根据数值判断健康状态
const getHealthStatus = (subName: string, subRes: string) => {
  const value = parseFloat(subRes);

  switch (subName) {
    case "血糖":
      if (value < 3.9)
        return {
          status: "偏低",
          color: "bg-blue-100 text-blue-600",
          bgColor: "bg-gradient-to-br from-blue-400 to-blue-500",
          dotColor: "bg-blue-400",
        };
      if (value > 6.1)
        return {
          status: "偏高",
          color: "bg-orange-100 text-orange-600",
          bgColor: "bg-gradient-to-br from-orange-400 to-orange-500",
          dotColor: "bg-orange-400",
        };
      return {
        status: "正常",
        color: "bg-green-100 text-green-600",
        bgColor: "bg-gradient-to-br from-green-400 to-green-500",
        dotColor: "bg-green-400",
      };
    case "血氧":
      if (value < 95)
        return {
          status: "偏低",
          color: "bg-red-100 text-red-600",
          bgColor: "bg-gradient-to-br from-red-400 to-red-500",
          dotColor: "bg-red-400",
        };
      return {
        status: "正常",
        color: "bg-green-100 text-green-600",
        bgColor: "bg-gradient-to-br from-green-400 to-green-500",
        dotColor: "bg-green-400",
      };
    case "体温":
      if (value < 36.0 || value > 37.2)
        return {
          status: "异常",
          color: "bg-red-100 text-red-600",
          bgColor: "bg-gradient-to-br from-red-400 to-red-500",
          dotColor: "bg-red-400",
        };
      return {
        status: "正常",
        color: "bg-green-100 text-green-600",
        bgColor: "bg-gradient-to-br from-green-400 to-green-500",
        dotColor: "bg-green-400",
      };
    case "心率":
      if (value < 60 || value > 100)
        return {
          status: "异常",
          color: "bg-orange-100 text-orange-600",
          bgColor: "bg-gradient-to-br from-orange-400 to-orange-500",
          dotColor: "bg-orange-400",
        };
      return {
        status: "正常",
        color: "bg-green-100 text-green-600",
        bgColor: "bg-gradient-to-br from-green-400 to-green-500",
        dotColor: "bg-green-400",
      };
    default:
      return {
        status: "正常",
        color: "bg-green-100 text-green-600",
        bgColor: "bg-gradient-to-br from-green-400 to-green-500",
        dotColor: "bg-green-400",
      };
  }
};

// 格式化显示值
const formatDisplayValue = (subName: string, subRes: string, updateTime?: string) => {
  const timeStr = updateTime ? ` (${updateTime})` : "";
  switch (subName) {
    case "血糖":
      return `血糖数值：${subRes} mmol/L${timeStr}`;
    case "血氧":
      return `血氧饱和度：${subRes}%${timeStr}`;
    case "血压":
      return `血压：${subRes} mmHg${timeStr}`;
    case "心率":
      return `心率：${subRes} 次/分${timeStr}`;
    case "体温":
      return `体温度数：${subRes}°C${timeStr}`;
    case "心电图":
      return `心电数值：${subRes}${timeStr}`;
    case "运动":
      return `运动分数：${subRes}${timeStr}`;
    default:
      return `${subName}：${subRes}${timeStr}`;
  }
};

// 编辑健康记录
const editHealthRecord = (record: any) => {
  editingRecord.value = record;
  editValue.value = record.value || record.subRes || '';
  showEditPopup.value = true;
};

// 确认编辑
const confirmEdit = async () => {
  if (!editValue.value.trim()) {
    Taro.showToast({
      title: "请输入数值",
      icon: "none",
    });
    return;
  }

  try {
    // 如果是固定项目，直接更新本地数据
    if (editingRecord.value && fixedHealthItems.value.includes(editingRecord.value)) {
      const itemIndex = fixedHealthItems.value.findIndex(item => item === editingRecord.value);
      if (itemIndex !== -1) {
        fixedHealthItems.value[itemIndex].value = editValue.value;
      }
      
      Taro.showToast({
        title: "修改成功",
        icon: "success",
      });

      // 关闭弹窗
      showEditPopup.value = false;
      editingRecord.value = null;
      editValue.value = "";
      return;
    }

    // 原有的API调用逻辑（用于动态数据）
    const { error, success } = await request.post(
      "/health_records/health_basepro/healthBaseProjectInfo/edit",
      {
        id: editingRecord.value.id,
        subRes: editValue.value,
      },
      {
        useErrMsg: true,
      }
    );

    if (!error && success) {
      Taro.showToast({
        title: "修改成功",
        icon: "success",
      });

      // 关闭弹窗
      showEditPopup.value = false;
      editingRecord.value = null;
      editValue.value = "";

      // 重新获取数据
      getHealthData();
    } else {
      Taro.showToast({
        title: "修改失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("修改失败:", error);
    Taro.showToast({
      title: "修改失败",
      icon: "none",
    });
  }
};

// 取消编辑
const cancelEdit = () => {
  showEditPopup.value = false;
  editingRecord.value = null;
  editValue.value = "";
};


// 页面加载时获取数据
onMounted(() => {
  getHealthData();

  // 监听刷新健康数据事件
  emitter.$on("refreshHealthData", () => {
    getHealthData();
  });
});

// 组件卸载时清理事件监听
onUnmounted(() => {
  emitter.$off("refreshHealthData");
});
</script>

<style lang="scss" scoped>
.btsc {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
}
</style>
